package com.yf.ability.office.service.impl;

import com.yf.base.api.exception.ServiceException;
import com.yf.ability.office.service.OfficeService;
import lombok.extern.log4j.Log4j2;
import org.jodconverter.core.DocumentConverter;
import org.jodconverter.core.document.DefaultDocumentFormatRegistry;
import org.jodconverter.core.office.OfficeException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.File;

/**
 * @author bool
 */
@Log4j2
@Component
public class OfficeServiceImpl implements OfficeService {



    @Lazy
    @Autowired

    private DocumentConverter converter;


    /**
     * 传入完整的URL路径
     * @param input
     * @param dist
     * @throws OfficeException
     */
    @Override
    public String convert(String input, String dist) throws ServiceException {

        log.info("++++++++++传入:"+input);

        //源文件读取不到
        File srcFile = new File(input);
        if(!srcFile.exists()){
            throw new ServiceException("输入文件不存在！");
        }

        log.info("++++++++++目标文件："+dist);

        //生成时要增加后.pdf后缀，否则无法转换
        File outputFile = new File(dist);

        //必须包含后缀才能转换
        try {
            converter.convert(srcFile)
                    .as(DefaultDocumentFormatRegistry.PDF)
                    .to(outputFile)
                    .execute();
            return dist;
        }catch (OfficeException e){
            e.printStackTrace();
            throw new ServiceException("文件转换过程发生错误："+e.getMessage());
        }

    }
}
